package com.yu.juctest;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    static Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) {
        for (int i = 1; i <=6 ; i++) {
            new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName() + "开始找车位");
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "已停车");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));//随机停5秒以下就走
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(Thread.currentThread().getName() + "不停了，走咯---------");
                    semaphore.release();
                }
            },i+"号车").start();
        }
    }
}
